import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get/get.dart';
import 'package:winkai/db/database.dart';
import 'package:winkai/dio/error_handle.dart';
import 'package:winkai/entity/role_info.dart';
import 'package:winkai/service/api_service.dart';
import 'package:winkai/widget/empty_layout.dart';

class DiscoverChildController extends GetxController {
  EmptyType? stateType = EmptyType.loading;
  bool isNoNetwork = false;
  int index = 0;
  int page = 1;
  int pageSize = 20;
  bool isLoadMore = false;
  List<RoleInfo> recordList = [];
  StreamSubscription<List<ConnectivityResult>>? _subscription;

  DiscoverChildController();

  @override
  void onInit() {
    super.onInit();
    listenerNetworkStatus();
  }

  @override
  void onClose() {
    super.onClose();
    _subscription?.cancel();
    _subscription = null;
  }

  void listenerNetworkStatus() {
    _subscription = Connectivity()
        .onConnectivityChanged
        .listen((List<ConnectivityResult> result) {
      if (result
          .where((element) => element != ConnectivityResult.none)
          .isNotEmpty) {
        if (stateType == null && recordList.isNotEmpty) {
          refreshData();
        }
      }
    });
  }

  void refreshData() {
    page = 1;
    var lastRecordLength = recordList.length;
    Future.wait([
      _getList(),
    ]).then((value) {
      update();
      if (page == 1 &&
          recordList.isNotEmpty &&
          lastRecordLength != recordList.length) {}
    });
  }

  void loadMore() async {
    page++;
    await _getList();
    update();
  }

  Future<void> _getList() async {
    var result = await ApiService().getRoleList();
    isNoNetwork = result.code == ExceptionHandle.socketError;
    List<RoleInfo>? list;
    if (index == 1) {
      list = result.data
          ?.where((element) => element.renderStyle == 'REALISTIC')
          .toList();
    } else if (index == 2) {
      list = result.data
          ?.where((element) => element.renderStyle == 'ANIME')
          .toList();
    } else {
      list = result.data;
    }
    if (page == 1) {
      recordList.clear();
    }
    if (list?.isNotEmpty == true) {
      if (list!.length < pageSize) {
        isLoadMore = false;
      } else {
        isLoadMore = true;
      }
      recordList.addAll(list);
      for (var element in list) {
        await rootDb.userDao.insertOrUpdate(
          id: element.id ?? '',
          nickname: element.name ?? '',
          avatar: element.avatar ?? '',
          age: element.age,
          renderStyle: element.renderStyle,
          aboutMe: element.aboutMe,
          greetings: element.greetings,
        );
      }
    } else {
      if (page > 1) {
        page--;
        isLoadMore = true;
      } else {
        isLoadMore = false;
      }
    }
    stateType = null;
  }
}
